"""
价格趋势验证器
避免瞬时跌破导致的误触发，确认真实趋势
"""
import logging
from ..base import SignalValidator, ValidationContext, ValidationResult

logger = logging.getLogger('PriceTrendValidator')


class PriceTrendValidator(SignalValidator):
    """
    价格趋势验证器
    检查：
    1. 跌破幅度是否足够（避免正常波动误判）
    2. 跌破是否持续（连续多分钟在MA5下方）
    """
    
    def __init__(self, min_break_pct: float = 0.005, lookback: int = 2):
        """
        Args:
            min_break_pct: 最小跌破幅度（相对MA5）
            lookback: 回看分钟数
        """
        self.min_break_pct = min_break_pct
        self.lookback = lookback
    
    def validate(self, context: ValidationContext) -> ValidationResult:
        """验证价格趋势"""
        if context.current_index < self.lookback:
            return ValidationResult(
                passed=False,
                validator_name=self.get_name(),
                details="数据不足",
                confidence=0.0
            )
        
        try:
            current_data = context.stock_data.iloc[context.current_index]
            current_price = current_data['close']
            ma5_current = current_data.get('MA5', current_price)
            
            # 检查跌破幅度
            if ma5_current == 0:
                return ValidationResult(
                    passed=False,
                    validator_name=self.get_name(),
                    details="MA5为0，无法计算",
                    confidence=0.0
                )
            
            break_pct = (ma5_current - current_price) / ma5_current
            
            if break_pct < self.min_break_pct:
                return ValidationResult(
                    passed=False,
                    validator_name=self.get_name(),
                    details=f"跌破幅度不足({break_pct:.2%} < {self.min_break_pct:.2%})",
                    confidence=break_pct / self.min_break_pct
                )
            
            # 检查持续性：连续多分钟在MA5附近或下方
            below_count = 0
            for i in range(max(0, context.current_index - self.lookback), context.current_index + 1):
                data = context.stock_data.iloc[i]
                price = data['close']
                ma5 = data.get('MA5', price)
                
                # 在MA5的0.2%范围内视为接近
                if price <= ma5 * 1.002:
                    below_count += 1
            
            passed = below_count >= self.lookback
            confidence = below_count / (self.lookback + 1)
            
            return ValidationResult(
                passed=passed,
                validator_name=self.get_name(),
                details=f"连续{below_count}分钟在MA5附近 (需要{self.lookback})",
                confidence=confidence
            )
            
        except Exception as e:
            logger.warning(f"价格趋势验证异常: {e}")
            return ValidationResult(
                passed=False,
                validator_name=self.get_name(),
                details=f"验证异常: {str(e)}",
                confidence=0.0
            )
    
    def get_name(self) -> str:
        return "价格趋势确认"

